﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows;
using Infov1.ViewModels;
using Infov1.Commands;
using Infov1.Models.WorkRecord;
using HandyControl.Controls;
public class EditWorkRecordViewModel : ViewModelBase
{
    private readonly ISqlSugarClient _db;
    private readonly WorkRecordModel _originalRecord;
    private readonly Action _refreshCallback;

    #region 属性

    /// <summary>
    /// 要编辑的记录
    /// </summary>
    private WorkRecordModel _record;
    public WorkRecordModel Record
    {
        get => _record;
        set => SetProperty(ref _record, value);
    }

    /// <summary>
    /// 处理时间（包含日期和时间）
    /// </summary>
    private DateTime _creationTime;
    public DateTime CreationTime
    {
        get => _creationTime;
        set
        {
            SetProperty(ref _creationTime, value);
            if (Record != null)
            {
                Record.CreationTime = value;
            }
        }
    }

    /// <summary>
    /// 是否远程处理
    /// </summary>
    private bool _isRemote;
    public bool IsRemote
    {
        get => _isRemote;
        set
        {
            SetProperty(ref _isRemote, value);
            if (Record != null)
            {
                Record.IsRemote = value;
                Record.HandleTypeText = value ? "远程" : "电话";
            }
        }
    }

    #endregion

    #region 命令
    public ICommand SaveCommand { get; }
    public ICommand CancelCommand { get; }
    #endregion

    /// <summary>
    /// 构造函数
    /// </summary>
    public EditWorkRecordViewModel(WorkRecordModel record, ISqlSugarClient db, Action refreshCallback)
    {
        _db = db;
        _originalRecord = record;
        _refreshCallback = refreshCallback;

        // 创建记录副本
        Record = new WorkRecordModel
        {
            RecordId = record.RecordId,
            CreationTime = record.CreationTime,
            CustomerId = record.CustomerId,
            Customer = record.Customer,
            Details = record.Details,
            Result = record.Result,
            IsRemote = record.IsRemote,
            HandleTypeText = record.HandleTypeText,
            CommTypeCode = record.CommTypeCode,
            CommType = record.CommType,
            Operator = record.Operator
        };

        // 初始化时间和远程处理状态
        CreationTime = record.CreationTime;
        IsRemote = record.IsRemote;

        // 初始化命令
        SaveCommand = new RelayCommand(ExecuteSave);
        CancelCommand = new RelayCommand(ExecuteCancel);
    }

    /// <summary>
    /// 保存记录
    /// </summary>
    private async void ExecuteSave()
    {
        try
        {
            // 更新数据库
            await _db.Updateable(Record)
                    .UpdateColumns(r => new {
                        r.Details,
                        r.Result,
                        r.IsRemote,
                        r.CreationTime,
                        r.HandleTypeText
                    })
                    .ExecuteCommandAsync();

            // 显示成功消息
            Growl.Success("保存成功！");

            // 刷新主界面
            _refreshCallback?.Invoke();

            // 关闭窗口
            CloseWindow();
        }
        catch (Exception ex)
        {
            Growl.Error($"保存失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 取消编辑
    /// </summary>
    private void ExecuteCancel()
    {
        CloseWindow();
    }

    /// <summary>
    /// 关闭编辑窗口
    /// </summary>
    protected override void CloseWindow()
    {
        if (Application.Current.Windows.OfType<HandyControl.Controls.Window>()
            .FirstOrDefault(w => w.DataContext == this) is HandyControl.Controls.Window window)
        {
            window.Close();
        }
    }
}
